<template>
  <custom-dialog v-model="visible" title="查询配置" width="1000px" @closed="handleClose">
    <el-tabs v-model="activeName">
      <el-tab-pane label="过滤条件" name="filters">
        <el-button
            type="primary"
            round
            :disabled="Object.keys(conditionList).length !== 0"
            @click="addConditionItem"
        >添加条件
        </el-button
        >
        <el-button
            type="primary"
            round
            :disabled="Object.keys(conditionList).length !== 0"
            @click="addConditionGroup"
        >添加条件组
        </el-button>
        <template
            v-if="conditionList && Object.keys(conditionList).length !== 0"
        >
          <condition-group
              v-if="Object.keys(conditionList).includes('filters')"
              v-bind="props"
              :list="conditionList"
              @on-delete="onDelete"
          ></condition-group>
          <div class="condtionBox" v-else>
            <condition-item v-bind="$props" :item="conditionList"/>
            <i
                class="iconfont icon-delete"
                @click="onDelete(conditionList.privateKey)"
            ></i>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane label="排序" name="sorts">
        <el-button type="primary" round @click="addSortItem">添加</el-button>
        <el-table
            :data="sortList"
            border
            style="width: 100%; margin-top: 10px"
        >
          <el-table-column prop="fieldName" label="字段">
            <template #default="scope">
              <el-select
                  v-model="scope.row.fieldName"
                  style="width: 100%"
                  placeholder="字段"
                  clearable filterable
              >
                <el-option
                    v-for="(item, index) in props.fieldDefinitions"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="isAscending" label="排序方式">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.isAscending"
                  active-text="升序"
                  inactive-text="降序"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="scope">
              <el-button
                  @click="onSortDelete(scope.$index)"
                  type="text"
                  size="small"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="分页" name="pagination">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="启用">
            <el-switch v-model="pagination.enabled"></el-switch>
          </el-descriptions-item>
          <el-descriptions-item label="值来源">
            <el-radio-group v-model="pagination.isFrom">
              <el-radio
                  v-for="item in fromList"
                  :key="item.value"
                  :value="item.value"
              >{{ item.label }}
              </el-radio
              >
            </el-radio-group>
          </el-descriptions-item>
          <el-descriptions-item label="页码">
            <el-cascader
                v-if="pagination.isFrom == '2'"
                v-model="pagination.pageFrom"
                placeholder="页码"
                clearable
                :options="cptParamsOptions"
                :props="{ value: 'field',expandTrigger:'hover'}"
            ></el-cascader>
            <el-input-number
                v-else
                v-model="pagination.pageNumber"
                :min="1"
                placeholder="页码"
            ></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="每页条数">
            <el-cascader
                v-if="pagination.isFrom == '2'"
                v-model="pagination.pageSizeFrom"
                placeholder="每页条数"
                clearable
                :options="cptParamsOptions"
                :props="{ value: 'field',expandTrigger:'hover' }"
            ></el-cascader>
            <el-input-number
                v-else
                v-model="pagination.pageSize"
                :min="1"
                placeholder="每页条数"
            ></el-input-number>
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="权限" name="permit">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="权限">
            <el-select
                v-model="permit"
                style="width: 100%"
                placeholder="字段"
                clearable filterable
            >
              <el-option
                  v-for="(item, index) in permitOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </custom-dialog>
</template>
<script>
export default defineComponent({
  name: "QueryDialog",
})
</script>
<script setup>

import CustomDialog from "@/components/common/custom-dialog/index.vue";
import {deepClone, generateUUID} from "@/utils/util";
import {changeQueryData, getFilterItem} from "./utils";
import ConditionGroup from "@/components/event-behavior/query/condition-group.vue";
import ConditionItem from "@/components/event-behavior/query/condition-item.vue";

const props = defineProps({
// 页面组件选项
  paramsOptions: {
    type: Array,
    default() {
      return [];
    },
  },
  // 数据表dataModel
  fieldDefinitions: {
    type: Object,
    default() {
      return {};
    },
  },
  typeList: {
    type: Array,
    default() {
      return [
        {
          label: "LIKE（以sql为标准的模板匹配）",
          value: "LIKE",
        },
        {
          label: "NOTLIKE（以sql为标准的模板不匹配）",
          value: "NOTLIKE",
        },
        {
          label: "MATCHES（正常正则匹配）",
          value: "MATCHES",
        },
        {
          label: "NOTMATCHES（正常正则不匹配）",
          value: "NOTMATCHES",
        },
        {
          label: "LE（小于等于）",
          value: "LE",
        },
        {
          label: "LT（小于）",
          value: "LT",
        },
        {
          label: "EQ（等于）",
          value: "EQ",
        },
        {
          label: "GT（大于）",
          value: "GT",
        },
        {
          label: "GE（大于等于）",
          value: "GE",
        },
        {
          label: "NE（不等于）",
          value: "NE",
        },
        {
          label: "BETWEEN（在范围之间）",
          value: "BETWEEN",
        },
        {
          label: "NOTBETWEEN（不在范围之间）",
          value: "NOTBETWEEN",
        },
        {
          label: "IN（在给定values之内）",
          value: "IN",
        },
        {
          label: "NOTIN（不在给定values之内）",
          value: "NOTIN",
        },
        {
          label: "MISSINGVALUE（字段值不存在）",
          value: "MISSINGVALUE",
        },
        {
          label: "NOTMISSINGVALUE（字段值存在）",
          value: "NOTMISSINGVALUE",
        },
        {
          label: "NEAR（在指定距离之内）",
          value: "NEAR",
        },
        {
          label: "NOTNEAR（不在指定距离之内）",
          value: "NOTNEAR",
        },
        {
          label: "TAGGED（被指定标签标记）",
          value: "TAGGED",
        },
        {
          label: "NOTAGGED（未被指定标签标记）",
          value: "NOTAGGED",
        },
      ];
    },
  },
  // 是否有其他值来源
  hasOtherFrom: {
    type: Boolean,
    default: true,
  },
  parameterQuery: {
    type: Object,
    default() {
      return {}
    }
  }
})
const emits = defineEmits(['setCodeEditor'])
const visible = defineModel()
const paramsOptions = deepClone(props.paramsOptions)

const currItem = ref(deepClone(props.parameterQuery) || {})
console.log('111', currItem)
const conditionList = ref(currItem.value.conditionList || {})
const activeName = ref("filters")
const sortList = ref(currItem.value.sortList || [])
const pagination = ref(currItem.value.pagination || {
  enabled: false,
  pageNumber: null,
  pageSize: 10,
  isFrom: "1",
  pageFrom: "1",
  pageSizeFrom: ""
})
const permit = ref(currItem.value.permit || "")
const fromList = ref([
  {
    label: "自定义",
    value: "1",
  },
  {
    label: "页面组件",
    value: "2",
  },
])
const permitOptions = ref([
  {
    label: "公开",
    value: ""
  },
  {
    label: "本人",
    value: "1"
  },
  {
    label: "同部门",
    value: "2"
  },
  {
    label: "同部门及下级部门",
    value: "3"
  },
  {
    label: "同职位",
    value: "4"
  },
  {
    label: "同角色",
    value: "5"
  },
  {
    label: "同用户组",
    value: "6"
  }
])

const cptParamsOptions = computed(() => {
  const params = deepClone(props.paramsOptions.filter(item=>item.field!=3))
  params[1].children.filter(item => {
    return item.field.includes('datatable')
  }).forEach(item => {
    item.children = []
  })
  return params
})

const addConditionItem = () => {
  conditionList.value = deepClone(getFilterItem());
}
const addConditionGroup = () => {
  conditionList.value = {
    filters: [],
    type: "AND",
    isNot: false,
    privateKey: generateUUID(),
  }
}
const addSortItem = () => {
  sortList.value.push({
    fieldName: "",
    isAscending: false,
    isCaseSensitive: false,
  });
}
const onDelete = (privateKey) => {
  conditionList.value = {}
}
const handleClose = () => {
  visible.value = false;
}
const handleSubmit = () => {
  props.parameterQuery.conditionList = conditionList.value
  props.parameterQuery.sortList = sortList.value
  props.parameterQuery.pagination = pagination.value
  props.parameterQuery.permit = permit.value
  props.parameterQuery.value = formatQueryData(props.parameterQuery)
  emits('setCodeEditor', JSON.stringify(props.parameterQuery.value, null, 2))
  visible.value = false;
}
const formatQueryData = (item) => {
  let query = {
    permit: item.permit || "",
    filters: item.conditionList
        ? changeQueryData(deepClone(item.conditionList))
        : {},
    sorts: item.sortList ? deepClone(item.sortList) : [],
  };
  let pagination = {};
  if (item.pagination && item.pagination.enabled) {
    if (item.pagination.isFrom == "2") {
      // this.$set(pagination, "pageNumber", "");
      pagination.pageNumber = ""
      // this.$set(pagination, "pageSize", "");
      pagination.pageSize = "";
    } else {
      // this.$set(pagination, "pageNumber", item.pagination.pageNumber);
      pagination.pageNumber = item.pagination.pageNumber;
      // this.$set(pagination, "pageSize", item.pagination.pageSize);
      pagination.pageSize = item.pagination.pageSize;
    }
    // this.$set(query, "pagination", pagination);
    query.pagination = pagination
  }
  return query;
}

</script>

<style lang="scss" scoped>
.btnBox {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.condtionBox {
  display: flex;
  align-items: center;

  .iconfont {
    margin-left: 8px;
    cursor: pointer;

    &:hover {
      color: red;
    }

    :deep(.conditionItem) {
      flex: 1;
    }
  }
}

.label {
  margin-right: 10px;
}

:deep(.ep-tabs__content) {
  height: auto !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 16px;
  padding-right: 20px;
}
</style>
